<?php
/**
 * Description:
 *
 * @author      Eden
 * @datetime    2017/1/1 18:51
 * @copyright   WuHan HuQi Technology Co.,Ltd.
 * @url         http://cnhuqi.com
 */

require_once FCPATH . '/application/third_party/alipay/AopSdk.php';

class Callback extends CI_Controller
{
    private $pay_log = '';
    /**
     * 初始化
     */
    public function __construct()
    {
        parent::__construct();
        $this->pay_log = '/var/pay/Alipay-' . date('Y-m') . '.log';
    }

    public function index()
    {
    }

    /**
     * 回调通知URL
     */
    public function notify()
    {
        $return = 'failure';
        $aliError = '';
        $sn = '';
        $posts = array();

        do {
            if ($this->input->method(true) !== 'POST') {
                break;
            }

            $posts = $this->input->post();
            if (!alipay_verify($posts)) {
                $aliError = '鉴权错误';
                break;
            }

            if (empty($posts['trade_status']) || $posts['trade_status'] !== 'TRADE_SUCCESS') {
                break;
            }

            $sn = value($posts, 'out_trade_no');
            $total_amount = value($posts, 'total_amount');      // 订单金额
            $receipt_amount = value($posts, 'receipt_amount');  // 实收

            if (empty($sn) || empty($total_amount) || empty($receipt_amount)) {
                break;
            }

            $orders = $this->_getOrder($posts['out_trade_no']);
            $total = 0;
            $userid = 0;
            foreach ($orders as $order) {
                if ($order['payStatus'] == 6 || $order['status'] != 'Unpaid') {
                    $return = 'success';
                    break 2;
                }

                $total += intval($order['totalPrice']);
                $userid = $order['userId'];
            }

            $total_amount = intval($total_amount * 100);

            if ($total_amount != $total) {
                $aliError = '商品金额不符';
                break;
            }

            if ($this->modifyOrderStatus($sn, $userid, $posts)) {
                $return = 'success';
            }

        } while(false);

        if ($return == 'success') {
            file_put_contents($this->pay_log, '['.date('Y-m-d H:i:s').'] SUSSCESS SN: ' . $sn . PHP_EOL, FILE_APPEND);
        } else {
            file_put_contents($this->pay_log, '['.date('Y-m-d H:i:s').'] FAILED Error: ' . $aliError . PHP_EOL, FILE_APPEND);
            !empty($posts) && file_put_contents($this->pay_log, var_export($posts, true) . PHP_EOL, FILE_APPEND);
        }

        echo $return;
        exit;
    }

    public function modifyOrderStatus($sn, $userid, $posts)
    {

        try {
            $db = clone($this->db);
            $db->trans_start();

            $data = [
                'payWay' => 1,
                'payStatus' => 6,
                'status' => 'Pending',
                'merge' => 0
            ];

            $db->where('uuid', $sn);
            $db->update('user_order', $data);

            $affectedRows = $db->affected_rows();
            if ($affectedRows > 0) {
                $db->trans_complete();
            }
            return $db->trans_status();
        } catch(Exception $e) {
            file_put_contents($this->pay_log, $e->getMessage() . PHP_EOL, FILE_APPEND);
        }

        return false;

    }

    /**
     * 订单详情
     * @param string $sn
     * @return mixed
     */
    private function _getOrder($sn = '')
    {
        $db = clone($this->db);
        $q = $db->get_where('user_order', ['uuid' => $sn]);
        return $q->result_array();
    }
}
